package cn.kgc.controller;

import cn.kgc.base.entity.CartSkuInfo;
import cn.kgc.base.vo.OrderItemVo;
import cn.kgc.client.CartSkuInfoFeignClient;
import cn.kgc.commons.util.RedisUtil;
import cn.kgc.commons.util.UserContextHolder;
import cn.kgc.commons.vo.Result;
import cn.kgc.entity.Cart;
import cn.kgc.entity.CartItem;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * <p></p>
 *
 * @author 李孟鸠
 * @since 2022/12/16 0016 上午 9:04
 * 购物车控制器
 */
@RestController
@RequestMapping("/cart")
@Api(tags = "购物车接口")
public class CartController {


    @Resource
    private RedisUtil redisUtil;

    @Resource
    private CartSkuInfoFeignClient cartSkuInfoFeignClient;
    
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @GetMapping("/getOrderItemVo")
    @ApiOperation(value = "根据用户的ID获得购物车中已经被选中的商品",
            httpMethod = "GET",
            produces = "application/json;charest=utf-8",response = Result.class)
    @ApiImplicitParam(name = "memberId",value = "用户的ID",dataType="long",paramType = "query")
    @CrossOrigin
    public List<OrderItemVo>getOrderItemVo(long memberId){
        //购物车中的key
        String cartKey=memberId+"cart";
        List<OrderItemVo>result=new ArrayList<>(); //返回的订单中的商品信息

        if (!redisUtil.hasKey(cartKey)){ //判断用户的购物车是否有商品，如果没有商品返回空的集合
            return result;
        }
        //获得购物车中的商品信息， hash（key  hkey value）
        Iterator<Object> iterator = redisUtil.getHash(cartKey).values().iterator();

        while (iterator.hasNext()){
            CartItem cartItem=(CartItem) iterator.next();
            //判断购物车中的商品是否被选中
            if (cartItem.isCheck()){
                OrderItemVo orderItemVo=new OrderItemVo();
                BeanUtils.copyProperties(cartItem,orderItemVo);
                result.add(orderItemVo);
            }
        }
        return result;
    }

    /**
     * 向购物车中添加商品信息
     * @param skuId
     * @param count
     * @return
     */
    @PostMapping("/save")
    @ApiOperation(value = "向购物车中添加商品信息",httpMethod = "POST",
            produces = "application/json;charest=utf-8",response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "skuId",value = "skuId",paramType = "query",dataType = "Long"),
            @ApiImplicitParam(name = "count",value = "count",paramType = "query",dataType = "int"),
    })
    public boolean saveCartItem(@RequestParam(name = "skuId") Long skuId,
                           @RequestParam(name = "count",defaultValue = "1") Integer count){
        //登录用户的ID
        String userId = UserContextHolder.getInstance().getUserId();

        //key:用户的Id-cart    hk:skuId  hv:count
        String cacheKey=userId+"cart"; //redis中的key
        //hk: hash中的key
        String hk=skuId+"";
        //hv  CartItem对象



        //将商品保存到Redis中。hash类型保存数据
        //（1）判断购物车中已经有该商品，如果有购物车中的商品数量 增加
        if (redisUtil.hasKey(cacheKey,hk)) {
            //购物车中如果有该商品，购物车中的该商品的数量要增加
            CartItem cartItem = (CartItem) redisUtil.get(cacheKey, hk);
            cartItem.setCount(cartItem.getCount()+count);
            redisUtil.putKey(cacheKey,hk,cartItem);
        }
        //（2）购物车中没有该商品，将商品放入到购物车中
        //调用远程服务，获得商品信息
        Result<CartSkuInfo> cartSkuInfoResult = cartSkuInfoFeignClient.getCartSkuInfo(skuId);
        if (cartSkuInfoResult.getData() == null) {  //服务降级，没有获得商品信息。
            return false; //商品添加到购物车中失败
        }
        CartSkuInfo cartSkuInfo = cartSkuInfoResult.getData();


        CartItem hv=new CartItem();
        hv.setCount(count);
        hv.setPrice(cartSkuInfo.getPrice());
        hv.setCheck(true);
        hv.setImage(cartSkuInfo.getImage());
        hv.setSkuAttr(cartSkuInfo.getSkuAttr());
        hv.setSkuId(cartSkuInfo.getSkuId());
        hv.setSpuId(cartSkuInfo.getSpuId());
        hv.setTitle(cartSkuInfo.getTitle());
        redisUtil.putKey(cacheKey,hk,hv);
        return true;
    }

    //2查看购物车的商品
    @GetMapping("/getCart")
    @ApiOperation(value = "查看购物车信息",httpMethod = "GET",
            produces = "application/json;charest=utf-8",response = Result.class)
    @CrossOrigin
    public Cart getCart(){
        Cart cart=new Cart();
        //购物车中的商品种类
        //登录用户的ID
        String userId = UserContextHolder.getInstance().getUserId();
        String cacheKey=userId+"cart";
        if (!redisUtil.hasKey(cacheKey)){  //如果redis中没有购物车信息，直接返回一个空的cart对象
            return cart;
        }
        //获得购物车商品信息
            List<CartItem> cartItemList = new ArrayList<>();
            Map<Object, Object> map = redisUtil.getHash(cacheKey);
            Iterator<Object> iterator = map.values().iterator();
            while (iterator.hasNext()) {
                CartItem cartItem = (CartItem) iterator.next();
                cartItemList.add(cartItem);
            }
            cart.setItems(cartItemList);



        //选中商品数量
        //购物中存储的商品信息
        return cart;
    }

    //3删除购物车的商品
    @DeleteMapping("/delete")
    @ApiOperation(value = "删除购物车中的商品",httpMethod = "DELETE",
            produces = "application/json;charset=utf-8",response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "skuId",value = "skuId",paramType = "query",dataType = "Long"),
    })
    public boolean deleteCartItem(@RequestParam(name = "skuId") Long skuId){
        //登录用户的ID
//        String userId = UserContextHolder.getInstance().getUserId();
        String userId = "1";
        //key:用户的Id-cart    hk:skuId  hv:count
        String cacheKey=userId+"cart"; //redis中的key
        //hk: hash中的key
        String hk=skuId+"";
        //hv  CartItem对象
        redisUtil.deleteHashKey(cacheKey,hk);
        return true;
    }



}
